package cn.itcast.service.controller;

import cn.itcast.service.client.UserClient;
import cn.itcast.service.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
@RequestMapping("consumer/user")
//@DefaultProperties(defaultFallback = "fallBackMethod") // 指定一个类的全局熔断方法
public class UserController {

    //@Autowired
    //private RestTemplate restTemplate;

    @Autowired
    private UserClient userClient;

    // @Autowired
    ///private DiscoveryClient discoveryClient;

    @GetMapping
    @ResponseBody
    //@HystrixCommand // 标记该方法需要熔断
    public User queryUserById(@RequestParam("id") Long id) {
        /*if(id == 1){
            throw new RuntimeException("太忙了");
        }*/
        // List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // ServiceInstance instance = instances.get(0);
        // String user = this.restTemplate.getForObject("http://user-service/user/" + id, String.class);
        User user = this.userClient.queryUserById(id);
        return user;
    }

    /**
     * 熔断方法
     * 返回值要和被熔断的方法的返回值一致
     * 熔断方法不需要参数
     * @return
     */
    /*public String fallBackMethod(){
        return "请求繁忙，请稍后再试！";
    }*/
}
